<template>
  <div class="container-box">
    <el-dialog title="商品列表" :visible.sync="dialogVisible" :show-close="true" :close-on-click-modal="false" width="80%" @close="dialogVisible = false" custom-class="customDialog">
      <el-form class="demo-form-inline" :inline="true" :model="query">
        <template v-for="(colmun, index) in dialogColums.filter(d => d.isFilter)">
          <el-form-item v-if="colmun.key === 'cat_id'" :key="colmun.key" :label="colmun.title" :prop="colmun.key">
            <el-select v-model="query[colmun.key]" :placeholder="`请选择${colmun.title}`" filterable :clearable="colmun.clearable" @change="handleList(colmun.key, $event)">
              <el-option v-for="item in goodsCategory" :key="item.cat_id" :label="item.cat_name" :value="item.cat_id" />
            </el-select>
          </el-form-item>
          <el-form-item v-else-if="colmun.key === 'goods_name'" :key="colmun.key" :label="colmun.title" :prop="colmun.key">
            <el-select v-model="query[colmun.key]" :placeholder="`请选择${colmun.title}`" filterable :clearable="colmun.clearable" @change="handleList(colmun.key, $event)">
              <el-option v-for="item in goodsSelects" :key="item.value" :label="item.label" :value="item.label" />
            </el-select>
          </el-form-item>
          <el-form-item v-else-if="colmun.key === 'store_house_id'" :key="index" :label="colmun.title" :prop="colmun.key">
            <el-select v-model="query[colmun.key]" :placeholder="`请选择${colmun.title}`" :clearable="colmun.clearable" @change="handleList(colmun.key, $event)">
              <el-option v-for="item in storeHouseList" :key="item.id" :label="item.store_house_name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item v-else :key="index" :label="colmun.title">
            <el-input v-model="query[colmun.key]" :placeholder="`请输入${colmun.title}`" :clearable="colmun.clearable" @change="handleList(colmun.key, $event)" />
          </el-form-item>
        </template>
      </el-form>
      <el-table 
        ref="table" 
        :data="list" 
        :border="true" 
        default-expand-all
        :expand-row-keys="expandKeys" 
        :row-class-name="handleRowClass" 
        :row-key="record=>record.id+'_'+record.sku_id" 
        :tree-props="{children: 'attrValue', hasChildren: 'hasAttr'}" 
        highlight-current-row 
        @row-dblclick="rowDblclick"
        @expand-change="expandChange">
      <!-- <el-table :data="list" stripe :border="true" highlight-current-row @row-dblclick="rowDblclick" :row-class-name="handleRowClass"> -->
        <template v-for="(item, index) in dialogColums.filter(d => d.isTable)">
          <el-table-column :key="index" :prop="item.key" :label="item.title" :sortable="item.sortable">
            <template slot-scope="scope">
              <div v-html="handleRowResult(item, scope.row)"></div>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="saving" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="saving" @click="onDialogConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { goodsIndex
  // , goodsAdd, updateAttrConfig
} from '../../api/goods';
import { customerAdd, customerDetail } from '../../api/customer';
import curde from '@/mixins/curde'

export default {
  name: 'GoodsDialog',
  mixins: [curde],
  data() {
    return {
      dialogColums: [
        // { title: '仓库', key: 'store_house_id', type: 'text', clearable: true, isFilter: true, isTable: false, isForm: false },
        { title: '商品名称', key: 'goods_name', type: 'text', clearable: true, isFilter: true, isTable: true, isForm: true },
        { title: '商品全称', key: 'full_goods_name', type: 'text', isFilter: false, isTable: false, isForm: true },
        { title: '分类名称', key: 'cat_id', type: 'goodsCategoryDict', clearable: true, isFilter: false, isTable: false, isForm: true },
        { title: '排序', key: 'sort', type: 'number', sortable: true, isFilter: false, isTable: false, isForm: true },
        { title: '基本&辅助单位', key: 'unit_name', type: 'text', isFilter: false, isTable: false },
        { title: '单位换算', key: 'unit_convert', type: 'text', isFilter: false, isTable: false },
        { title: '基本单位', key: 'unit_name', type: 'text', isFilter: false, isTable: false, isForm: true },
        { title: '辅助单位', key: 'unit_name2', type: 'text', isFilter: false, isTable: false, isForm: true },
        { title: '基本单位换算', key: 'unit_convert', type: 'number', isFilter: false, isTable: false, isForm: true },
        { title: '辅助单位换算', key: 'unit_convert2', type: 'number', isFilter: false, isTable: false, isForm: true },
        { title: '库存', key: 'stock', type: 'text', isFilter: false, isTable: true }
      ],
      list: [],
      saving: false,
      dialogVisible: false,
      rules: {
        company_name: [
          { required: true, message: '请输入单位名称', trigger: ['change', 'blur'] }
          // { required: true, message: '分类名称已存在', validator: cateNameValidator }
        ],
        full_goods_name: [
          { required: true, message: '请输入商品名称-简称', trigger: ['change', 'blur'] }
          // { required: true, message: '分类名称已存在', validator: cateNameValidator }
        ],
        customer_name: [{ required: true, message: '请输入联系人', trigger: ['change', 'blur'] }],
        area: [{ required: true, message: '请输入联系人', trigger: ['change', 'blur'] }],
        company_type: [{ required: true, message: '请选择企业类型', trigger: ['change', 'blur'] }]
      },
      // dialogForm: {
      //   area: '广东省 广州市',
      //   area_address: '天健广场',
      //   bank: '123123',
      //   bank_name: '中国银行',
      //   company_name: '单位全称',
      //   full_company_name: '单位简称',
      //   company_type: '1',
      //   customer_name: '林',
      //   customer_type: '1',
      //   phone: '13812312312',
      //   remarks: '备注',
      //   status: '1',
      //   tel_phone: '020123123'
      // },
      dialogForm: {
        area: '',
        area_address: '',
        bank: '',
        bank_name: '',
        company_name: '',
        full_company_name: '',
        company_type: '',
        customer_name: '',
        customer_type: '1',
        phone: '',
        remarks: '',
        status: '1',
        tel_phone: ''
      },
      id: '',
      operateType: '',
      goodsSelects: [],
      expandKeys: []
    };
  },
  computed: {
    storeHouseDict() {
      return this.$store.getters.storeHouseDict;
    }
  },
  watch: {
    id(val) {
      if (val) {
        this.getDetail(val);
      }
    }
  },
  created() {
    this.getData();
  },
  methods: {
    expandChange(row, expand) {
      console.log('expandChange==', row, expand, this.expandKeys);
      if (!row) return;
      if (expand) {
        this.expandKeys.push(row.id+'_0');
      } else {
        const index = this.expandKeys.findIndex(d => d === row.id+'_0');
        if (index >= 0) {
          this.expandKeys.splice(index, 1)
        }
      }
      console.log('expandChange--this.expandKeys==', this.expandKeys);
    },
    // table row 样式
    handleRowClass({row, rowIndex}) {
      if (!row) {
        return '';
      }
      if (row.sku) {
        return 'goods_item_row';
      }
    },
    handleRowClass2({row, rowIndex}) {
      if (rowIndex === 0) {
        return 'goods_item_row';
      }
      else {
        const preRow = this.list[rowIndex - 1];
        if (preRow.id !== row.id) {
          return 'goods_item_row';
        }
        return '';
      }
    },
    rowDblclick(row, column, event) {
      console.log('rowDblclick==', row);
      if (!parseInt(row.sku_id)) {
        this.$message.warning('请选择具体的规格商品');
        return;
      }
      this.$emit('callback', 'rowDblclick', row);
    },
    // 显示弹框
    showDialog(operateType, params) {
      this.operateType = operateType;
      this.id = params?.id || '';
      this.dialogVisible = true;
    },
    // 关闭弹框
    closeDialog() {
      this.dialogVisible = false;
    },
    // 获取商品数据
    async getData() {
      const { data } = await goodsIndex();
      this.allList = data?.list || [];
      this.goodsSelects = [];  // 储存商品名称 过滤使用
      this.list = data.list.map(d => {
        this.goodsSelects.push({ label: d.goods_name, value: d.id });
        d.sku_id = '0';
        d.stock = 0;
        if (d.attrValue && d.attrValue.length) {
          d.attrValue = d.attrValue.map(t => {
            let attrItem = { ...d, ...t, sku_id: t.id };
            delete attrItem.attrValue;  // 移除多余字段
            const attrStock = t.attrStock || [];
            if (attrStock.length) {
              attrStock.forEach(s => {
                if (s.sku_id) {
                  d.stock += s.stock;
                }
              })
            }
            attrItem.stock = 0;  // 此处的 stock 是d.stock 需移除，防止以为是商品库存
            return attrItem;
          })
        }
        return d;
      });
    },
    // 把商品数据中的规格展开；attrConfig
    handleSpreadList() {
      const allList = this.$json.cloneDeep(this.allList);
      let spreadList = [];
      const socketData = {};
      const goodsSelects = [];  // 存储商品名称
      console.log('allList==', allList);
      allList.forEach(d => {
        // 收集商品名称；
        goodsSelects.push({ label: d.goods_name, value: d.id });

        const attrValue = d.attrValue || [];

        if (attrValue.length > 0) {
          const goodsItem = attrValue.map(attr => {
            const attrItem = Object.assign(d, { attrConfigValue: attr, sku_id: attr.id });
            return this.$json.cloneDeep(attrItem);
          })
          spreadList = spreadList.concat(goodsItem);
        }
        else {
          spreadList.push({ ...d, attrConfigValue: null });
        }
      })
      console.log('spreadList==', spreadList);
      this.spreadList = spreadList;
      this.goodsSelects = goodsSelects;
      this.socketData = socketData;
      this.handleList();
    },
    // 把商品数据中的规格展开；
    handleSpreadList2() {
      const allList = this.$json.cloneDeep(this.allList);
      let spreadList = [];
      const socketData = {};
      const goodsSelects = [];
      allList.forEach(d => {
        // 收集商品名称；
        goodsSelects.push({ label: d.goods_name, value: d.id });

        // 判断商品单规格 ｜ 多规格
        let attrConfig = [];
        if (d?.attrConfig?.config) {
          attrConfig = JSON.parse(d?.attrConfig?.config || '[]')
        }
        // 多规格
        if (attrConfig.length > 0) {
          const goodsItem = attrConfig.map(attr => {
            // socketData[`${d.id}_${attr.sku}`] = attr
            const attrItem = Object.assign(d, { attrConfigValue: attr, sku_id: attr.id });
            return this.$json.cloneDeep(attrItem);
          })
          spreadList = spreadList.concat(goodsItem);
        }
        else {
          spreadList.push({ ...d, attrConfigValue: null });
        }
      })
      this.spreadList = spreadList;
      this.goodsSelects = goodsSelects;
      this.socketData = socketData;
      this.handleList();
    },
    // 展示符合条件的数据
    handleList() {
      this.list = this.filterData(this.spreadList, this.createPayload(this.query));
      console.log('goodsDialog--this.list==', this.list);
      this.paging.total = this.list.length;
    },

    async getDetail(id) {
      const res = await customerDetail({ id: id || this.id });
      console.log('customerDetail--res==', res);
    },
    // dialog 提交；
    async onDialogConfirm() {
      let isValid = false;
      console.log('onDialogConfirm--this.$refs.dialogForm.==', this.$refs.dialogForm);
      this.$refs.dialogForm.validate(valid => {
        console.log('onDialogConfirm--valid==', valid);
        isValid = valid;
      })
      console.log('onDialogConfirm--this.saving ==', this.saving, isValid);
      if (this.saving) return this.$message.error('请勿重复提交');
      if (!isValid) return;
      // this.$message.error('请检查提交内容');

      this.saving = true;
      try {
        const payload = this.$json.cloneDeep(this.dialogForm);
        payload.full_company_name = payload.company_name;
        const res = await customerAdd(payload);
        // console.log('customerAdd--res==', res);
        if (res.data) {
          if (res.data?.code < 0) {
            this.$message({ message: res.data?.msg || '操作失败', type: 'error' })
          }
          else {
            this.closeDialog();
            this.$message({ message: '添加成功', type: 'success' })
            this.$emit('callback', true, res.data);
          }
        }
        else {
          this.$message({ message: res?.msg || '操作失败', type: 'error' })
        }

        // this.$emit(true, { ...res });
        // if (data && data.length === 2) {
        //   if (data[1]) {
        //     this.getData();
        //     this.$message.success('添加成功')
        //     this.dialogVisible = false;
        //   }
        //   else {
        //     this.$message.error(`添加失败: ${payload.goods_name} ${payload.full_goods_name} 已存在`)
        //   }
        // }
        // else {
        //   this.$message.error(`异常：添加失败`)
        // }
      }
      catch (e) {
        console.log('customerAdd--e==', e);
      }
      this.saving = false;
    },
    // 处理table 单元格显示；
    handleRowResult(item, row) {
      // console.log('handleRowResult--item', item, row);
      const value = row[item.key] || '';
      if (item.key === 'goods_name' || item.key === 'full_goods_name') {
        // const sku = row.attrConfigValue && row.attrConfigValue.sku ? row.attrConfigValue.sku : '';
        return `<strong>${value} ${row?.sku || ''}</strong>`;
      }
      if (item.key === 'stock') { // 库存
        
        const attrStock = row.attrStock || [];
        if (attrStock.length > 0) {
          const skus = attrStock;
          return skus.map(d => {
            let skuValue = '';
            if (!d.sku_id) {
              return '0';
            }
            if (d.stock && row.unit_name2 && row.unit_convert !== row.unit_convert2) {
              const unitNum = d.stock % row.unit_convert2;
              const unitNum2 = Math.floor(d.stock / row.unit_convert2);
              if (unitNum2) {
                skuValue = `${unitNum2}${row.unit_name2}`;
              }
              if (unitNum) {
                skuValue = skuValue + `${unitNum}${row.unit_name}`;
              }
              // skuValue = `${unitNum2}${row.unit_name2}${unitNum}${row.unit_name}`
            }
            else {
              skuValue = `${d.stock}${row.unit_name}`
            }
            let storeName = d.store_house_id ? this.storeHouseDict[d.store_house_id].store_house_name : '';
            // if (storeName && storeName.indexOf('-')) {
            //   const indexOf = storeName.indexOf('-');
            //   indexOf < storeName.length-1 && (storeName = storeName.slice(indexOf+1))
            // }
            return (`${storeName}: ${skuValue}`)
            // return (`${this.storeHouseDict[d.store_house_id].store_house_name}: ${skuValue}`)
          }).join('\n')
        }
        return '';
        // const socketKey = `${d.id}_${attr.store_house_id}_${attr.sku}`
        // if (row.stock && row.unit_name2 && row.unit_convert !== row.unit_convert2) {
        //   const unitNum = row.stock % row.unit_convert2;
        //   const unitNum2 = Math.floor(row.stock / row.unit_convert2);
        //   // return `${unitNum2}${row.unit_name2}${unitNum}${row.unit_name}`
        //   let skuValue = '';
        //   if (unitNum2) {
        //     skuValue = `${unitNum2}${row.unit_name2}`;
        //   }
        //   if (unitNum) {
        //     skuValue = skuValue + `${unitNum}${row.unit_name}`;
        //   }
        //   return skuValue;
        // }
        // return `${row.stock}${row.unit_name}`
      }
      // if (item.key === 'cat_id') {
      //   const category = this.goodsCategoryDict[value]
      //   return category?.cat_name || value
      // }
      if (item.key === 'unit_name') {
        return `${row.unit_name} / ${row.unit_name2 || '-'}`
      }
      if (item.key === 'unit_convert') {
        if (row.unit_name2) {
          return `${row.unit_convert2}${row.unit_name} = ${row.unit_convert}${row.unit_name2}`
        }
        return
      }
      return value;
    }
  }
}

</script>
<style lang="scss" scoped>
.container-box {
  padding: 20px;
}
.el-dialog.customDialog {
  .el-table {
    ::v-deep .cell {
      white-space: pre-line !important;
      display: flex;
    }
    ::v-deep .goods_item_row {
      background-color: #fdf5e6;
    }
  }
}


.container-box {
  ::v-deep .el-table .cell {
    white-space: pre-line !important;
  }
  .el-pagination {
    margin-top: 10px;
    text-align: right;
  }
}
</style>
